package linter.linterjava.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import linter.linterjava.POJO.DO.Article;
import linter.linterjava.POJO.DO.ArticleLikes;
import linter.linterjava.mapper.ArticleMapper;
import linter.linterjava.service.ArticleLikesService;
import linter.linterjava.mapper.ArticleLikesMapper;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static linter.linterjava.custom.CustomResultType.LIKES_ERROR;
import static linter.linterjava.custom.CustomResultType.LIKES_SUCCESS;

/**
* @author 北煜
* @description 针对表【article_likes(文章点赞表)】的数据库操作Service实现
* @createDate 2024-07-07 12:15:00
*/
@Service
public class ArticleLikesServiceImpl extends ServiceImpl<ArticleLikesMapper, ArticleLikes>
    implements ArticleLikesService{

    @Resource
    ArticleLikesMapper articleLikesMapper;
    @Resource
    ArticleMapper articleMapper;


    @Cacheable(value = "articleLikes", key = "#{ 'userLikes_' + T(String).valueOf(#uuid) }")
    public List<Long> userLikeForArticle(Long uuid) {
        List<ArticleLikes> articleLikes = articleLikesMapper.selectList(
                new QueryWrapper<ArticleLikes>().eq("user_id", uuid).eq("is_delete",0)
        );
        return articleLikes.stream().map(ArticleLikes::getArticleId).collect(Collectors.toList());
    }
    @Override
    public String like(Long uuid, Long articleId) {
        Date date = new Date();
        Article article1 = articleMapper.selectById(articleId);
        Integer like = article1.getLikeNub();
        // 先检查用户是否点赞过，点赞过就不可以再次点赞
        List<Long> articleIds = userLikeForArticle(uuid);
        if (articleIds.contains(articleId)) { return "您已经点过赞了"; }
        // 用户没有点赞过，可以点赞
        ArticleLikes articleLikes = new ArticleLikes();
        articleLikes.setUserId(uuid);
        articleLikes.setArticleId(articleId);
        articleLikes.setCreateTime(date);
        articleLikes.setUpdataTime(date);
        int flag = articleLikesMapper.insert(articleLikes);
        Article article = new Article();
        article.setLikeNub(like + 1);
        article.setUpdataTime(new Date());
        flag += articleMapper.update(article, new QueryWrapper<Article>()
                .eq("id", articleId).eq("is_delete",0));
        return flag > 0 ? LIKES_ERROR : LIKES_SUCCESS;
    }


}




